<template>
  <a-table
    :columns="columns"
    :data="tempOkrData"
    :pagination="false"
    :bordered="{ wrapper: true, cell: true }"
    stripe
    :spanMethod="dataSpanMethod"
  >
    <template #index="{ record }">
      {{ record.rowIndex + 1 }}
    </template>
    <template #achievementWeight="{ record }">
      {{ record.achievementWeight }}%
    </template>
    <template #weight="{ record }"> {{ record.weight }}% </template>
    <template #optional="{ record, rowIndex }">
      <a-tooltip content="编辑">
        <IconFont
          type="icon-edit"
          :size="26"
          :style="{
            marginRight: '10px',
            cursor: 'pointer'
          }"
          @click="goEdit(record, record.indexRow)"
        />
      </a-tooltip>
      <a-tooltip content="删除" position="left">
        <a-popconfirm content="是否确认删除该条数据?" @ok="del(rowIndex)">
          <icon-font
            type="icon-delete"
            :size="26"
            :style="{
              cursor: 'pointer',
              marginRight: '10px'
            }"
          />
        </a-popconfirm>
      </a-tooltip>
    </template>
  </a-table>
  <a-button v-if="!props.review" type="text" @click="add">新增指标</a-button>
  <IndexDrawer
    v-model:visible="drawerVisible"
    @okrIndexEmit="submit"
    :data="currData"
  />
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { PerformanceKeyPerformanceIndexLibraryUse } from '@/apis/management/performance/baseSetting/template/type';
import IndexDrawer from './IndexDrawer.vue';
// import IndexDrawer from '@/views/Management/Performance/BaseSetting/Index/OkrIndex/IndexDrawer.vue';
import { useVModel } from '@vueuse/core';

const props = withDefaults(
  defineProps<{
    review?: boolean;
    data?: PerformanceKeyPerformanceIndexLibraryUse[];
  }>(),
  { data: () => [] }
);
const emit = defineEmits(['update:visible', 'handleOk', 'update:data']);
const handleOk = () => {
  emit('handleOk');
};
const change = () => {
  emit('update:data', tableData.value);
};
const tableData = useVModel(props, 'data', emit);

const columns: any = reactive([
  {
    title: '序号',
    render: ({ record }: { record: any }) => record.indexRow + 1,
    width: 70,
    align: 'center'
  },
  {
    title: '目标(O)',
    dataIndex: 'name',
    slotName: 'name',
    width: 300,
    align: 'center'
  },
  {
    title: 'O权重/分值',
    dataIndex: 'weight',
    slotName: 'weight',
    width: 200,
    align: 'center'
  },
  {
    title: '关键成果(KRs)',
    dataIndex: 'achievementName',
    slotName: 'achievementName',
    align: 'center'
  },
  {
    title: 'KR权重',
    dataIndex: 'achievementWeight',
    slotName: 'achievementWeight',
    width: 100,
    align: 'center'
  }
]);
onMounted(() => {
  if (!props.review) {
    columns.push({
      title: '操作',
      dataIndex: 'optional',
      slotName: 'optional',
      width: 120,
      align: 'center',
      fixed: 'right'
    });
  }
});
const currData = ref<PerformanceKeyPerformanceIndexLibraryUse>({});
const drawerVisible = ref(false);
const editIndex = ref(-1); //编辑项的下标，用以判断新增和编辑，下标小于0是新增数据。大于等于0则是修改此下标的值
const add = () => {
  editIndex.value = -1;
  currData.value = {
    weightType: 1,
    status: 1,
    weight: 0,
    name: '',
    performanceKeyResultsIndexLibraryUse: [{ result: '', weight: 0 }]
  };
  drawerVisible.value = true;
};
const del = (index: number) => {
  if (!tableData.value?.length) return;
  tableData.value.splice(index, 1);
  change();
};
const goEdit = (
  data: PerformanceKeyPerformanceIndexLibraryUse,
  index: number
) => {
  console.log('index', index);

  editIndex.value = index;
  currData.value = data;
  drawerVisible.value = true;
};
const submit = (data: PerformanceKeyPerformanceIndexLibraryUse) => {
  //判断是新增还是编辑
  if (editIndex.value < 0) {
    //新增
    tableData.value?.push(data);
  } else {
    //编辑
    if (!tableData.value?.length) return;

    tableData.value[editIndex.value] = data;
  }
  change();
};

let tempOkrData: any = computed(() => {
  let newArr: any = [];
  if (tableData.value && tableData.value.length > 0) {
    tableData.value?.forEach((item: any, index: number) => {
      if (item.performanceKeyResultsIndexLibraryUse?.length) {
        item.performanceKeyResultsIndexLibraryUse?.forEach((item2: any) => {
          newArr.push({
            ...item,
            indexRow: index,
            achievementName: item2.result,
            achievementWeight: item2.weight
          });
        });
      } else {
        newArr.push({ ...item, indexRow: index });
      }
    });
    console.log('nsssewArr', newArr);

    return newArr;
  } else return [];
});
// 表格合并
const dataSpanMethod = (datas: any) => {
  const { record, rowIndex, columnIndex, column } = datas;
  // 处理rowSpan
  const obj = {
    rowspan: 2,
    colspan: 1
  };
  const enums = ['achievementName', 'achievementWeight', 'indexLibrary'];
  let arr = tempOkrData.value.filter(
    (item: any) => item?.indexRow === record?.indexRow
  );
  if (
    !enums.includes(column.dataIndex) &&
    tempOkrData.value[rowIndex - 1]?.indexRow !== record?.indexRow
  ) {
    obj.rowspan = arr?.length;
  } else {
    obj.rowspan = 0;
  }

  return obj;
};
</script>

<style lang="less" scoped>
//
</style>
